package cn.tedu.boot31.controller;

import cn.tedu.boot31.entity.Product;
import cn.tedu.boot31.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author wxd
 * @version 1.0
 * -@RestController注解相当于在每一个方法上面添加@ResponseBody注解
 */
@RestController
public class ProductController {
    @Autowired
    ProductMapper mapper;
    @RequestMapping("/insert")
    public String insert(Product product) {
        System.out.println("product = " + product);
        mapper.insert(product);
        return "商品添加成功!<a href='/'>返回首页</a>";
    }
    @RequestMapping("/select")
    public String select() {
        List<Product> list =  mapper.select();
//        String html="<table border=1>";
//        html+="<caption>商品列表</caption>";
//        html+="<tr><th>序号</th><th>标题</th><th>价格</th><th>销量</th></tr>";
//        for (Product p : list) {
//            html += "<tr>";
//            html += "<td>"+p.getId()+"</td>";
//            html += "<td>"+p.getTitle()+"</td>";
//            html += "<td>"+p.getPrice()+"</td>";
//            html += "<td>"+p.getSaleCount()+"</td>";
//            html += "</tr>";
//        }
//        html+="</table>";
//        return html;
        StringBuilder html = new StringBuilder("<table border=1>");
        html.append("<caption>商品列表</caption>").append("<tr><th>序号</th><th>标题</th><th>价格</th><th>销量</th><th>操作</th></tr>");
        for (Product p : list) {
            html.append("<tr>");
            html.append("<td>").append(p.getId()).append("</td>");
            html.append("<td>").append(p.getTitle()).append("</td>");
            html.append("<td>").append(p.getPrice()).append("</td>");
            html.append("<td>").append(p.getSaleCount()).append("</td>");
            html.append("<td><a href='/delete?id=").append(p.getId()).append("'>删除</a></td>");
            html.append("</tr>");
        }
        html.append("</table>");
        return html.toString();
    }

    @RequestMapping("/delete")
    public String delete(int id) {
        System.out.println("id = " + id);
        mapper.deleteById(id);
        return "删除完成!<a href='/select'>返回列表页面</a>";
    }

    @RequestMapping("/update")
    public String update(Product product) {
        System.out.println("product = " + product);
        mapper.update(product);
        return "修改完成!<a herf='/select'>返回列表页面</a>";
    }
}
